package com.nie.orderfood.controller;

import com.nie.orderfood.Utils.ResultUtils;
import com.nie.orderfood.VO.ProductInfoVO;
import com.nie.orderfood.VO.ProductVO;
import com.nie.orderfood.VO.ResultVO;
import com.nie.orderfood.entity.ProductCategory;
import com.nie.orderfood.entity.ProductInfo;
import com.nie.orderfood.service.ProductCategoryService;
import com.nie.orderfood.service.ProductInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: orderfood
 * @description: 买家端商品信息
 * @author: NieMiao
 * @create: 2018-10-08 14:29
 **/
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategoryService productCategoryService;

    /**
    * @Description: 买家端返回商品列表
    * @Param: []
    * @return: com.nie.orderfood.VO.ResultVO
    * @Author: NieMiao
    * @Date: 2018/10/8
    */
    @RequestMapping("/list")
    public ResultVO List(){
        //1.查询所有上架商品
        List<ProductInfo> products = productInfoService.findAllUp();

        //2.查询所有上架的商品所属的类型的集合
        List<Integer> productCategoryTypes = products.stream()
                .map(e -> e.getCategoryType()).
                        collect(Collectors.toList());
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(productCategoryTypes);

        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory: productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : products) {
                if (productCategory.getCategoryType().equals(productInfo.getCategoryType())) {
                    ProductInfoVO productInfoVo = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVo);
                    productInfoVOList.add(productInfoVo);
                }
            }
            productVO.setProducts(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultUtils.success(productVOList);

    }
}
